package handlers

import (
	"admin-pro/cache"
	"admin-pro/models"
	"admin-pro/pkg"
	"github.com/gin-gonic/gin"
	"strconv"
	"time"
)

func Login(c *gin.Context) {
	username := c.PostForm("username")
	password := c.PostForm("password")
	if username == "" || password == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "不能为空",
		})
		return
	}
	var user models.User
	redis_key := "login_" + username
	errData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Int()
	if errData >= 3 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "密码错误3次，禁止登录",
		})
		return
	}
	err := models.DB.Where("username=?", username).Debug().First(&user).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "账号或密码错误",
		})
		return
	}
	if user.ID == 0 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "账号或密码错误",
		})
		return
	}
	if pkg.Md5(password) != user.Password {
		cache.Rdb.Incr(cache.Ctx, redis_key)
		if errData == 2 {
			cache.Rdb.Set(cache.Ctx, redis_key, 3, time.Hour*2)
			c.JSON(200, gin.H{
				"code": 500,
				"msg":  "密码错误3次，封禁2小时",
			})
			return
		}
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "密码错误",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 500,
		"msg":  "登录成功",
		"data": user,
	})
	return
}
func CreateRN(c *gin.Context) {
	rid, _ := strconv.Atoi(c.Query("rid"))
	nid, _ := strconv.Atoi(c.Query("nid"))
	if rid == 0 || nid == 0 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "不能为空",
		})
		return
	}
	data := models.RoleNode{
		Rid: rid,
		Nid: nid,
	}
	err := models.DB.Debug().Create(&data).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "分配失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "分配成功",
	})
	return
}

//func UserRoleList(c *gin.Context) {
//	uid := c.Query("uid")
//	//SELECT * FROM roles
//	//JOIN user_roles ON user_roles.rid=roles.id
//	//WHERE user_roles.uid=1
//	var role []models.Role
//	models.DB.Table("roles").
//		Joins("LEFT JOIN user_roles ON user_roles.rid=roles.id").
//		Where("user_roles.uid=?", uid).
//		Find(&role)
//	c.JSON(200, gin.H{
//		"code": 200,
//		"msg":  "ok",
//		"data": role,
//	})
//	return
//}

//SELECT
//users.username,
//roles.role_name
//FROM
//  user_roles
//LEFT JOIN users ON users.id=user_roles.uid
//LEFT JOIN roles ON roles.id=user_roles.rid
